/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package com.alien.admin.modules.deploy.rest;

import com.alien.admin.annotation.Log;
import com.alien.admin.modules.deploy.domain.DeployRec;
import com.alien.admin.modules.deploy.domain.UserHotProject;
import com.alien.admin.modules.deploy.service.DeployRecService;
import com.alien.admin.modules.deploy.service.DeployService;
import com.alien.admin.modules.deploy.service.UserHotProjectService;
import com.alien.admin.modules.deploy.service.dto.DeployRecDto;
import com.alien.admin.modules.deploy.service.dto.DeployRecQueryCriteria;
import com.alien.admin.utils.SecurityUtils;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import java.sql.Timestamp;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @author zhouseyi
* @date 2021-09-22
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "部署记录管理")
@RequestMapping("/api/deployRec")
public class DeployRecController {

    private final DeployRecService deployRecService;
    private final DeployService deployService;
    private final UserHotProjectService userHotProjectService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('deployRec:list')")
    public void download(HttpServletResponse response, DeployRecQueryCriteria criteria) throws IOException {
        deployRecService.download(deployRecService.queryAll(criteria), response);
    }

    /**
     * 这个方法返回了所有的字段，性能比较差。
     *
     * @param criteria
     * @param pageable
     * @return
     */
    @GetMapping
    @Log("查询部署记录")
    @ApiOperation("查询部署记录")
    @PreAuthorize("@el.check('deployRec:list')")
    public ResponseEntity<Object> query(DeployRecQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(deployRecService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    /**
     * 这个返回的字段比较少，性能比较好。
     *
     * @param criteria
     * @param pageable
     * @return
     */
    @GetMapping(value = "query2")
    @Log("查询部署记录")
    @ApiOperation("查询部署记录")
    @PreAuthorize("@el.check('deployRec:list')")
    public ResponseEntity<Object> query2(DeployRecQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(deployRecService.queryAll2(criteria,pageable),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增部署记录")
    @ApiOperation("新增部署记录")
    @PreAuthorize("@el.check('deployRec:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody DeployRec resources){
        return new ResponseEntity<>(deployRecService.create(resources),HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改部署记录")
    @ApiOperation("修改部署记录")
    @PreAuthorize("@el.check('deployRec:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody DeployRec resources){
        deployRecService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除部署记录")
    @ApiOperation("删除部署记录")
    @PreAuthorize("@el.check('deployRec:del')")
    @DeleteMapping
    public ResponseEntity<Object> delete(@RequestBody Long[] ids) {
        deployRecService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @PostMapping("/createProjectDeploy")
    @Log("新增服务部署")
    @ApiOperation("新增服务部署")
    @PreAuthorize("@el.check('deployRec:add')")
    public ResponseEntity<Object> createProjectDeploy(@Validated @RequestBody DeployRecQueryCriteria criteria) {
        // 记录用户部署的项目到user_hot_deploy表中
        UserHotProject resources = new UserHotProject();
        resources.setUserId(SecurityUtils.getCurrentUserId());
        resources.setProjectId(Long.valueOf(criteria.getProjectId()));
        resources.setEnv(criteria.getEnv());
        resources.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        resources.setCreateTime(new Timestamp(System.currentTimeMillis()));

        userHotProjectService.createOrUpdate(resources);
        return new ResponseEntity<>(deployService.createProjectDeploy(criteria),HttpStatus.CREATED);
    }

    @PostMapping("/queryDeploy")
    @Log("查询单个部署记录")
    @ApiOperation("查询单个部署记录")
    @PreAuthorize("@el.check('deployRec:list')")
    public ResponseEntity<Object> queryDeploy(@RequestBody DeployRecQueryCriteria criteria){
        DeployRecDto deployRecDto = deployRecService.findById(criteria.getId());
        return new ResponseEntity<>(deployRecDto,HttpStatus.OK);
    }

    @PostMapping("/buildImage")
    @Log("构建镜像")
    @ApiOperation("构建镜像")
    @PreAuthorize("@el.check('deployRec:edit')")
    public ResponseEntity<Object> buildImage(@RequestBody DeployRecQueryCriteria criteria){
        DeployRec deployRec = deployService.buildImage(criteria.getId());
        return new ResponseEntity<>(deployRec,HttpStatus.OK);
    }

    @PostMapping("/deploy")
    @Log("容器部署")
    @ApiOperation("容器部署")
    @PreAuthorize("@el.check('deployRec:edit')")
    public ResponseEntity<Object> deploy(@RequestBody DeployRecQueryCriteria criteria){
        DeployRec deployRec = deployService.deploy(criteria.getId());
        return new ResponseEntity<>(deployRec,HttpStatus.OK);
    }

    @PostMapping("/deployByHistory")
    @Log("历史版本部署")
    @ApiOperation("历史版本部署")
    @PreAuthorize("@el.check('deployRec:add')")
    public ResponseEntity<Object> deployByHistory(@Validated @RequestBody DeployRecQueryCriteria criteria) {
        return new ResponseEntity<>(deployService.deployByHistory(criteria.getId()), HttpStatus.CREATED);
    }

    @PostMapping("/queryLog")
    @Log("服务日志")
    @ApiOperation("服务日志")
    @PreAuthorize("@el.check('deployRec:list')")
    public ResponseEntity<Object> queryLog(@RequestBody DeployRecQueryCriteria criteria){
        String log = deployService.queryLog(criteria.getProjectId(), criteria.getEnv());
        return new ResponseEntity<>(log,HttpStatus.OK);
    }
}
